package Z11_20_pool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author： pang-yun
 * @date： 2021-11-22 10:08
 * 功能目的 ：用于 fork - join  线程池
 */
@Slf4j
public class ForkPool {
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool(5);
        System.out.println(forkJoinPool.invoke(new MyTask(5)));
    }

    static class MyTask extends RecursiveTask<Integer>{
        private int num;
        public MyTask(int num) {
            this.num = num;
        }

        @Override
        public String toString() {
            return "MyTask{" +
                    "num=" + num +
                    '}';
        }

        @Override
        protected Integer compute() {
            //如果 n 已经为 1  可以求得结果
            if (num==1){
                return 1;
            }
            // 将任务 进行拆分(fork)
            MyTask newTask = new MyTask(num - 1);
            newTask.fork();
            log.info(" fork()  {} + {}", num , newTask);

            // 合并 join 结果
            int result = newTask.join() + num;
            System.out.println(toString());
            return  result;
        }
    }
}
